package controller;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

@ApplicationScoped
@ManagedBean
public class LoginBean {
	private String username;
	private String password;
	private String error;
	
	private static final String[] users = {"rusapozhdm:rjyutybfkmyj","user:password"}; 
	
	public void setUser(String username){
		this.username = username;
	}
	
	public String getUser(){
		return username;
	}
	
	public void setPassword(String password){
		this.password = password;
	}
	
	public String getPassword(){
		return password;
	}
	
	public void setError(String error){
		this.error = error;
	}
	
	public String getError(){
		return error;
	}
	
	public String login(){
		
		if (username.equals("user") && password.equals("password")){
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", 1);
			return "main?faces-redirect=true";
		}
		else{
			setError("User and password are invalid!");
			return "login?faces-redirect=true";
		}
	}
	
	public String doLogin() {
        // Get every user from our sample database :)
        for (String user: users) {
            String dbUsername = user.split(":")[0];
            String dbPassword = user.split(":")[1];
             
            // Successful login
            if (dbUsername.equals(username) && dbPassword.equals(password)) {
            	FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", 1);
            	return "/main.xhtml?faces-redirect=true";
            }
        }
         
        // Set login ERROR
        FacesMessage msg = new FacesMessage("Login error!", "ERROR MSG");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        FacesContext.getCurrentInstance().addMessage(null, msg);
         
        // To to login page
        return "/login.xhtml?faces-redirect=true";
         
    }
}

